Security News
Weekly Downloads Now Available in npm Package Search Results
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
The emittery npm package is an asynchronous event emitter library. It allows you to emit and listen for events in a way that is not tied to the DOM and is more flexible than the native Node.js EventEmitter. It supports async iteration of events, namespaced events, and ensures that listeners are called in the order they were added.
Emitting and listening to events
This feature allows you to create an event emitter, listen for events, and emit events with data. Listeners are invoked with the data passed to `emit`.
{"const Emittery = require('emittery');\nconst emitter = new Emittery();\n\nemitter.on('event', data => {\n console.log(data);\n});\n\nemitter.emit('event', 'some data');\n//=> 'some data'"}
Asynchronous event emission
This feature allows you to wait for all the event listeners to finish processing before continuing execution. It's useful when you need to ensure that all side effects have been completed before proceeding.
{"const Emittery = require('emittery');\nconst emitter = new Emittery();\n\n(async () => {\n await emitter.emit('event', 'some data');\n console.log('Event emitted');\n})();"}
Namespaced events
This feature allows you to create and listen for namespaced events, which can help in organizing event types and avoiding name collisions.
{"const Emittery = require('emittery');\nconst emitter = new Emittery();\n\nemitter.on('namespace:event', () => {\n console.log('Namespaced event fired');\n});\n\nemitter.emit('namespace:event');\n//=> 'Namespaced event fired'"}
Clearing listeners
This feature allows you to remove listeners from events, either all listeners from a specific event or all listeners from all events.
{"const Emittery = require('emittery');\nconst emitter = new Emittery();\n\nconst listener = () => {\n console.log('Event fired');\n};\nemitter.on('event', listener);\n\nemitter.clearListeners('event');\nemitter.emit('event');\n// No output, because the listener was removed"}
eventemitter3 is a high performance EventEmitter. It has a similar API to Node.js's native EventEmitter but is optimized for performance. Unlike emittery, it does not support async event emission.
mitt is a tiny functional event emitter / pubsub. It provides a similar event emitter functionality with a smaller footprint. However, it does not have async event handling capabilities like emittery.
Simple and modern async event emitter
It's only ~200 bytes minified and gzipped. I'm not fanatic about keeping the size at this level though.
It's works in Node.js and the browser (using a bundler).
Emitting events asynchronously is important for production code where you want the least amount of synchronous operations.
$ npm install emittery
const Emittery = require('emittery');
const emitter = new Emittery();
emitter.on('🦄', data => {
console.log(data);
// '🌈'
});
emitter.emit('🦄', '🌈');
The above only works in Node.js 8 or newer. For older Node.js versions you can use require('emittery/legacy')
.
Subscribe to an event.
Returns an unsubscribe method.
Using the same listener multiple times for the same event will result in only one method call per emitted event.
Remove an event subscription.
Subscribe to an event only once. It will be unsubscribed after the first event.
Returns a promise for the event data when eventName
is emitted.
emitter.once('🦄').then(data => {
console.log(data);
//=> '🌈'
});
emitter.emit('🦄', '🌈');
Trigger an event asynchronously, optionally with some data. Listeners are called in the order they were added, but execute concurrently.
Returns a promise for when all the event listeners are done. Done meaning executed if synchronous or resolved when an async/promise-returning function. You usually wouldn't want to wait for this, but you could for example catch possible errors. If any of the listeners throw/reject, the returned promise will be rejected with the error, but the other listeners will not be affected.
Same as above, but it waits for each listener to resolve before triggering the next one. This can be useful if your events depend on each other. Although ideally they should not. Prefer emit()
whenever possible.
If any of the listeners throw/reject, the returned promise will be rejected with the error and the remaining listeners will not be called.
Subscribe to be notified about any event.
Returns a method to unsubscribe.
Remove an onAny
subscription.
Clear all event listeners on the instance.
If eventName
is given, only the listeners for that event are cleared.
The number of listeners for the eventName
or all events if not specified.
Definition for emittery
and emittery/legacy
are included. Use import Emittery = require('emittery')
or import Emittery = require('emittery/legacy')
to load the desired implementation.
The default Emittery
class does not let you type allowed event names and their associated data. However you can use Emittery.Typed
with generics:
import Emittery = require('emittery');
const ee = new Emittery.Typed<{value: string}, 'open' | 'close'>();
ee.emit('open');
ee.emit('value', 'foo\n');
ee.emit('value', 1); // TS compilation error
ee.emit('end'); // TS compilation error
Listeners are not invoked for events emitted before the listener was added. Removing a listener will prevent that listener from being invoked, even if events are in the process of being (asynchronously!) emitted. This also applies to .clearListeners()
, which removes all listeners. Listeners will be called in the order they were added. So-called any listeners are called after event-specific listeners.
Note that when using .emitSerial()
, a slow listener will delay invocation of subsequent listeners. It's possible for newer events to overtake older ones.
EventEmitter
in Node.js?There are many things to not like about EventEmitter
: its huge API surface, synchronous event emitting, magic error event, flawed memory leak detection. Emittery has none of that.
EventEmitter
synchronous for a reason?Mostly backwards compatibility reasons. The Node.js team can't break the whole ecosystem.
It also allows silly code like this:
let unicorn = false;
emitter.on('🦄', () => {
unicorn = true;
});
emitter.emit('🦄');
console.log(unicorn);
//=> true
But I would argue doing that shows a deeper lack of Node.js and async comprehension and is not something we should optimize for. The benefit of async emitting is much greater.
emit()
?No, just use destructuring:
emitter.on('🦄', ([foo, bar]) => {
console.log(foo, bar);
});
emitter.emit('🦄', [foo, bar]);
MIT © Sindre Sorhus
FAQs
Simple and modern async event emitter
The npm package emittery receives a total of 28,712,439 weekly downloads. As such, emittery popularity was classified as popular.
We found that emittery demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Socket's package search now displays weekly downloads for npm packages, helping developers quickly assess popularity and make more informed decisions.
Security News
A Stanford study reveals 9.5% of engineers contribute almost nothing, costing tech $90B annually, with remote work fueling the rise of "ghost engineers."
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.